﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Frw
{
    public class Validator : BusinessClassBase<IValidator, Validator>, IValidator
    {
        private ICollection<ValidationResult> m_results = null;

        public ICollection<ValidationResult> Results
        {
            get { return m_results; }
        }

        public bool Validate<T>(T objectToValidate)
        {
            bool retValue = false;

            foreach (MetadataTypeAttribute attrib in objectToValidate.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true))
            {
                System.ComponentModel.TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(objectToValidate.GetType(), attrib.MetadataClassType), objectToValidate.GetType());
            }

            var context = new ValidationContext(objectToValidate, serviceProvider: null, items: null);
            m_results = new List<ValidationResult>();
            
            retValue = System.ComponentModel.DataAnnotations.Validator.TryValidateObject(objectToValidate, context, m_results, validateAllProperties: true);
                    
            return retValue;
        }


    }
}
